<script>
import { defineComponent, reactive, toRefs, onMounted, ref } from "vue";
import DefaultButton from "./DefaultButton.vue";
import {
  getUserList,
  addNewUser,
  delUser,
  editUser,
  getProblemList,
} from "@/api/user.js";

export default defineComponent({
  name: "UserTable",
  components: {
    DefaultButton,
  },
  props: {
    width: {
      type: String,
      default: "80%",
    },
    // list: {
    //   type: Array,
    //   default: () => {
    //     return [
    //       { userName: "admin", userType: 0, id: 1 },
    //       { userName: "user1", userType: 1, id: 2 },
    //     ];
    //   },
    // },
  },
  setup() {
    // 密码验证
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (state.selectUser.repassword !== "") {
          if (!updateForm.value) return;
          updateForm.value.validateField("repassword");
        }
        callback();
      }
    };
    //确认密码验证
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"));
      } else if (value !== state.selectUser.password) {
        callback(new Error("确认密码不一致"));
      } else {
        callback();
      }
    };

    // 安全问题验证不重复
    const validatePass3 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择安全问题1"));
      } else {
        if (state.addUserInfo.safetyProblem1 !== "") {
          if (!addForm.value) return;
          if (
            state.addUserInfo.safetyProblem1 ===
            state.addUserInfo.safetyProblem2
          ) {
            callback(new Error("请选择不同的安全问题"));
          }
          addForm.value.validateField("safetyProblem2");
        }
        callback();
      }
    };

    const validatePass4 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择安全问题2"));
      } else {
        if (state.addUserInfo.safetyProblem2 !== "") {
          if (!addForm.value) return;

          if (
            state.addUserInfo.safetyProblem1 ===
            state.addUserInfo.safetyProblem2
          ) {
            callback(new Error("请选择不同的安全问题"));
          }

          addForm.value.validateField("safetyProblem1");
        }
        callback();
      }
    };

    const state = reactive({
      currentSelect: -1,
      userList: [],
      indexStart: 1,
      loading: false,
      isShowAddUser: false,
      addUserInfo: {
        userName: "",
        password: "",
        userType: "0",
        answer1: "",
        answer2: "",
        safetyProblem1: "",
        safetyProblem2: "",
      },
      rules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [{ validator: validatePass, trigger: ["blur", "change"] }],
        repassword: [{ validator: validatePass2, trigger: ["blur", "change"] }],
      },
      addRules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        answer1: [
          {
            required: true,
            message: "请输入答案1",
            trigger: "blur",
          },
        ],
        safetyProblem1: [
          { validator: validatePass3, trigger: ["blur", "change"] },
        ],
        safetyProblem2: [
          { validator: validatePass4, trigger: ["blur", "change"] },
        ],
        answer2: [
          {
            required: true,
            message: "请输入答案2",
            trigger: "blur",
          },
        ],
      },

      selectUser: {},
      isShowDelUser: false,
      isShowUpdate: false,
      isShowSafe: false,
      problemList: [],
    });

    const addForm = ref(null);
    const updateForm = ref(null);
    const safeForm = ref(null);

    const safeRules = {
      answer1: [
        {
          required: true,
          message: "请输入答案1",
          trigger: "blur",
        },
      ],
      safetyProblem1: [{ validator: validatePass3, trigger: "blur" }],
      safetyProblem2: [{ validator: validatePass4, trigger: "blur" }],
      answer2: [
        {
          required: true,
          message: "请输入答案2",
          trigger: "blur",
        },
      ],
    };

    const userTypeList = [
      {
        id: "0",
        name: "普通用户",
      },
      {
        id: "1",
        name: "管理员",
      },
    ];

    onMounted(() => {
      getList();
      getProList();
    });

    //获取用户列表
    const getList = () => {
      state.loading = true;
      getUserList().then(
        (res) => {
          if (res.code === 200) {
            state.userList = res.data.users;
          } else {
            ElMessage({
              message: res.message,
              type: "warning",
            });
          }
          state.loading = false;
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };

    //获取用户安全问题列表
    const getProList = () => {
      getProblemList().then(
        (res) => {
          if (res.code === 200) {
            state.problemList = res.data.problems;
            state.problemList.forEach((item) => {
              if (item.id !== null) {
                item.id = +item.id;
              }
            });
          } else {
            ElMessage({
              message: res.message,
              type: "warning",
            });
          }
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };

    //点击新增
    const addUser = () => {
      state.isShowAddUser = true;
    };

    //关闭新增弹窗
    const closeAddUser = () => {
      state.isShowAddUser = false;
      addForm.value.resetFields();
    };
    //保存新增
    const saveAddUser = () => {
      addForm.value.validate((valid) => {
        if (valid) {
          addNewUser(state.addUserInfo).then(
            (res) => {
              if (res.code === 200) {
                ElMessage({
                  message: "保存成功",
                  type: "success",
                  offset: 400,
                });
              } else {
                ElMessage({
                  message: res.message,
                  type: "warning",
                });
              }
              closeAddUser();
              getList();
            },
            (err) => {
              ElMessage({
                message: err.message,
                type: "warning",
              });
            }
          );
        } else {
          return false;
        }
      });
    };

    //选择单行时
    const rowClick = (row) => {
      if (!row) return;
      state.currentSelect = 1;
      state.selectUser = { ...row };
      state.selectUser.password = "";
      state.selectUser.repassword = "";
    };

    //删除用户
    const deleteUser = () => {
      if (state.currentSelect === -1) return;
      state.isShowDelUser = true;
    };

    //关闭删除弹窗
    const closeDelUser = () => {
      state.isShowDelUser = false;
    };

    //确认删除
    const saveDeleteUser = () => {
      delUser(state.selectUser.id).then(
        (res) => {
          if (res.code === 200) {
            ElMessage({
              message: "删除成功",
              type: "success",
              offset: 400,
            });
          } else {
            ElMessage({
              message: res.message,
              type: "warning",
            });
          }
          state.currentSelect = -1;
          closeDelUser();
          getList();
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };

    //点击修改弹窗
    const updateUser = () => {
      if (state.currentSelect === -1) return;
      state.isShowUpdate = true;
    };

    //关闭修改
    const closeUpdateUser = () => {
      state.isShowUpdate = false;
      // updateForm.value.resetFields();
    };
    //确认修改
    const saveUpdateUser = () => {
      updateForm.value.validate((valid) => {
        if (valid) {
          editUser(state.selectUser).then(
            (res) => {
              if (res.code === 200) {
                ElMessage({
                  message: "修改成功",
                  type: "success",
                  offset: 400,
                });
              } else {
                ElMessage({
                  message: res.message,
                  type: "warning",
                });
              }
              state.currentSelect = -1;
              closeUpdateUser();
              getList();
            },
            (err) => {
              ElMessage({
                message: err.message,
                type: "warning",
              });
            }
          );
        } else {
          return false;
        }
      });
    };

    //点击安全问题
    const showSafe = () => {
      if (state.currentSelect === -1) return;
      state.isShowSafe = true;
    };

    // 关闭安全问题
    const closeSafe = () => {
      state.isShowSafe = false;
      // safeForm.value.resetFields();
    };
    // 确认安全问题

    const saveSafe = () => {
      // if (state.selectUser.safetyProblem1 === state.selectUser.safetyProblem2) {
      //   ElMessage({
      //     message: "请选择不同的问题",
      //     type: "warning",
      //     offset: 200,
      //   });
      //   return;
      // }
      safeForm.value.validate((valid) => {
        if (valid) {
          editUser(state.selectUser).then(
            (res) => {
              if (res.code === 200) {
                ElMessage({
                  message: "保存成功",
                  type: "success",
                  offset: 400,
                });
              } else {
                ElMessage({
                  message: res.message,
                  type: "warning",
                });
              }
              state.currentSelect = -1;
              closeSafe();
              getList();
            },
            (err) => {
              ElMessage({
                message: err.message,
                type: "warning",
              });
            }
          );
        } else {
          return false;
        }
      });
    };

    return {
      ...toRefs(state),
      getList,
      getProList,
      addUser,
      closeAddUser,
      saveAddUser,
      rowClick,
      deleteUser,
      closeDelUser,
      saveDeleteUser,
      updateUser,
      saveUpdateUser,
      closeUpdateUser,
      showSafe,
      closeSafe,
      saveSafe,
      safeRules,
      userTypeList,
      addForm,
      updateForm,
      safeForm,
    };
  },
});
</script>

<template>
  <div class="component-user-table-container" :style="{ width }">
    <div class="table-operation-bar">
      <div class="caption">用户列表</div>
      <div class="button-group">
        <default-button
          @click="addUser"
          class="operation-button"
          title="添加"
          :width="70"
        />
        <default-button
          class="operation-button"
          title="修改"
          :width="70"
          @click="updateUser"
          :disabled="currentSelect === -1"
        />
        <default-button
          class="operation-button"
          title="删除"
          @click="deleteUser"
          :width="70"
          :disabled="currentSelect === -1"
        />
        <default-button
          class="operation-button"
          title="账号安全设置"
          :width="120"
          @click="showSafe"
          :disabled="currentSelect === -1"
        />
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table
      class="userTable"
      v-loading="loading"
      :data="userList"
      :border="true"
      height="550"
      highlight-current-row
      style="width: 100%"
      @current-change="rowClick"
    >
      <el-table-column
        type="index"
        :index="indexStart"
        label="序号"
        width="180"
      />
      <el-table-column prop="userName" label="用户名" width="180" />
      <el-table-column prop="userType" label="用户类型">
        <template #default="scope">
          {{ scope.row.userType === "1" ? "管理员" : "普通用户" }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增用户 -->
    <el-dialog
      class="userForm"
      v-model="isShowAddUser"
      title="添加用户"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeAddUser"
      width="20vw"
    >
      <div class="main">
        <el-form
          :model="addUserInfo"
          label-width="auto"
          :rules="addRules"
          ref="addForm"
        >
          <el-form-item label="用户名:" prop="userName">
            <el-input v-model="addUserInfo.userName" />
          </el-form-item>
          <el-form-item label="用户密码:" prop="password">
            <el-input type="password" v-model="addUserInfo.password" />
          </el-form-item>
          <el-form-item label="用户类型:">
            <el-select v-model="addUserInfo.userType" placeholder="请选择">
              <el-option
                class="selectType"
                v-for="item in userTypeList"
                :key="item.id"
                size="mini"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="安全问题1:" prop="safetyProblem1">
            <el-select
              v-model="addUserInfo.safetyProblem1"
              placeholder="请选择问题"
            >
              <el-option
                class="selectType"
                v-for="item in problemList"
                :key="item.id"
                size="mini"
                :label="item.problem"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="答案1:" prop="answer1">
            <el-input v-model="addUserInfo.answer1" />
          </el-form-item>

          <el-form-item label="安全问题2:" prop="safetyProblem2">
            <el-select
              v-model="addUserInfo.safetyProblem2"
              placeholder="请选择问题"
            >
              <el-option
                class="selectType"
                v-for="item in problemList"
                :key="item.id"
                size="mini"
                :label="item.problem"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="答案2:" prop="answer2">
            <el-input v-model="addUserInfo.answer2" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="footer">
          <el-button @click="closeAddUser"> 取消 </el-button>
          <el-button @click="saveAddUser">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog
      class="updateUser"
      v-model="isShowUpdate"
      title="修改用户"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeUpdateUser"
      width="18vw"
    >
      <div class="main">
        <el-form
          :model="selectUser"
          label-width="auto"
          :rules="rules"
          ref="updateForm"
        >
          <el-form-item label="用户名:" prop="userName">
            <el-input v-model="selectUser.userName" />
          </el-form-item>
          <el-form-item label="用户类型:">
            <el-select v-model="selectUser.userType" placeholder="请选择">
              <el-option
                class="selectType"
                v-for="item in userTypeList"
                :key="item.id"
                size="mini"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户密码:" prop="password">
            <el-input type="password" v-model="selectUser.password" />
          </el-form-item>
          <el-form-item label="用户密码确认:" prop="repassword">
            <el-input type="password" v-model="selectUser.repassword" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="footer">
          <el-button @click="closeUpdateUser"> 取消 </el-button>
          <el-button @click="saveUpdateUser">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除用户 -->
    <el-dialog
      class="deleteUser"
      v-model="isShowDelUser"
      title="删除用户"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeDelUser"
      width="18vw"
    >
      <div class="main">
        确定删除用户: {{ selectUser ? selectUser.userName : "" }}
      </div>
      <template #footer>
        <div class="footer">
          <el-button @click="closeDelUser"> 取消 </el-button>
          <el-button @click="saveDeleteUser">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 安全问题 -->
    <el-dialog
      class="userSafe"
      v-model="isShowSafe"
      title="账号安全设置"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeSafe"
      width="35vw"
    >
      <div class="main">
        <el-form
          :model="selectUser"
          label-width="auto"
          :rules="safeRules"
          ref="safeForm"
        >
          <el-form-item label="安全问题1:" prop="safetyProblem1">
            <el-select
              v-model="selectUser.safetyProblem1"
              placeholder="请选择问题"
            >
              <el-option
                class="selectType"
                v-for="item in problemList"
                :key="item.id"
                size="mini"
                :label="item.problem"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="答案1:" prop="answer1">
            <el-input v-model="selectUser.answer1" />
          </el-form-item>

          <el-form-item label="安全问题2:" prop="safetyProblem2">
            <el-select
              v-model="selectUser.safetyProblem2"
              placeholder="请选择问题"
            >
              <el-option
                class="selectType"
                v-for="item in problemList"
                :key="item.id"
                size="mini"
                :label="item.problem"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="答案2:" prop="answer2">
            <el-input v-model="selectUser.answer2" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="footer">
          <el-button @click="closeSafe"> 取消 </el-button>
          <el-button @click="saveSafe">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.component-user-table-container {
  .table-operation-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #74bcff;
    height: 42px;
    padding: 0 28px;

    .caption {
      color: #000000;
      font-size: 16px;
      font-weight: 600;
    }

    .button-group {
      display: flex;
      align-items: center;

      .operation-button {
        margin-right: 12px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .main {
    .selectType {
      width: 15vw;
    }
  }
}
</style>
